<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PropLuck extends Base
{
    protected $prop_luck_table = 'prop_luck';
    protected $prop_luck_log_table = 'prop_luck_log';
    protected $prop_luck_poll_table = 'prop_luck_poll';
    protected $propLuckInValKey = 'PROP:LUCK:INVAL:';
    protected $propLuckOutValKey = 'PROP:LUCK:OUTVAL:';


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function getPropLuckById($id)
    {
        $db = DB::table($this->prop_luck_table);
        $getData = $db->where([$this->primaryKey => $id])->first();
        return self::objToArray($getData);
    }

    public function getPropLuckPollByLuckId($propLuckId)
    {
        $db = DB::table($this->prop_luck_poll_table);
        $getData = $db->where(["prop_luck_id" => $propLuckId])->orderBy("price", "asc")->get();
        return self::objToArray($getData);
    }

    /**
     * 用户抽奖记录-创建
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @return bool
     * */
    public function updateOrInsertPropLuckLog($data = [], $type = 'insert')
    {
        switch ($type) {
            case 'insert':
                $ret = DB::table($this->prop_luck_log_table)->insertGetId($data);
                break;
            default:
                $ret = false;
                break;
        }
        return $ret;
    }

    public function incInVal($propLuckId, $val){
        return Redis::INCRBY($this->propLuckInValKey . $propLuckId, $val);
    }

    public function getInVal($propLuckId){
        $val = Redis::GET($this->propLuckInValKey . $propLuckId);
        if (empty($val)){
            return 0;
        }
        return intval($val);
    }

    public function incOutVal($propLuckId, $val){
        return Redis::INCRBY($this->propLuckOutValKey . $propLuckId, $val);
    }

    public function getOutVal($propLuckId){
        $val = Redis::GET($this->propLuckOutValKey . $propLuckId);
        if (empty($val)){
            return 0;
        }
        return intval($val);
    }
}